<template>
  <div class="filter">
    <div class="filter-item">
      <label for="">设备名称：</label>
      <el-input
        v-model="searchForm.facilityName"
        placeholder="请输入设备名称"
        style="width: 145px"
      />
    </div>
    <div class="filter-item">
      <label for="">设备分级：</label>
      <el-select
        v-model="searchForm.facilityLevel"
        class="m-2"
        placeholder="请选择设备分级"
        style="width: 145px"
      >
        <el-option
          v-for="item in facilityLevelList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <div class="filter-item">
      <label for="">规格型号：</label>
      <el-input
        v-model="searchForm.specificationModel"
        placeholder="请输入规格型号"
        style="width: 145px"
      />
    </div>
    <div class="filter-item">
      <label for="">设备地点：</label>
      <el-input
        v-model="searchForm.facilityLocations"
        placeholder="请输入设备地点"
        style="width: 145px"
      />
    </div>
    <div class="filter-item">
      <label for="">资产编号：</label>
      <el-input
        v-model="searchForm.assetNumber"
        placeholder="请输入资产编号"
        style="width: 145px"
      />
    </div>
    <div class="filter-item">
      <label for="">所属单位：</label>
      <el-select
        v-model="searchForm.depId"
        class="m-2"
        placeholder="请选择所属单位"
        style="width: 145px"
        :disabled="localTypeUnit != '1'"
        @change="depIdChange"
      >
        <el-option
          v-for="item in depIdList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <div class="filter-item">
      <label for="">设备分类：</label>
      <el-select
        v-model="searchForm.facilitySort"
        class="m-2"
        placeholder="请选择设备分类"
        style="width: 145px"
      >
        <el-option
          v-for="item in facilitySortList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <div class="filter-item">
      <label for="">供应商/厂家：</label>
      <el-input
        v-model="searchForm.facilitySupplier"
        placeholder="请输入供应商/厂家"
        style="width: 145px"
      />
    </div>
    <div class="filter-item">
      <label for="">设备状态：</label>
      <el-select
        v-model="searchForm.facilityState"
        class="m-2"
        placeholder="请选择设备状态"
        style="width: 145px"
      >
        <el-option
          v-for="item in facilityStateList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <div class="filter-item">
      <el-button type="primary" @click="search">查询</el-button>
    </div>
    <div class="filter-item">
      <el-button type="primary" @click="reset">重置</el-button>
    </div>
  </div>
  <div class="options">
    <div class="overview">
      <!-- 设备概括 -->
      <el-tag class="ml-2" size="large"
        >设备总数({{ equipmentOverview.total }})</el-tag
      >
      <el-tag class="ml-2" size="large" type="success"
        >正常({{ equipmentOverview.useCount }})</el-tag
      >
      <el-tag class="ml-2" size="large" type="info"
        >备用({{ equipmentOverview.standbyCount }})</el-tag
      >
      <el-tag class="ml-2" size="large" type="warning"
        >维修({{ equipmentOverview.repairCount }})</el-tag
      >
      <el-tag class="ml-2" size="large" type="danger"
        >已报废({{ equipmentOverview.scrapCount }})</el-tag
      >
    </div>
    <div class="operations">
      <el-button @click="add">新增设备</el-button>
      <el-button @click="batchAdd">批量新增</el-button>
      <el-button @click="batchEdit">批量修改</el-button>
      <el-button @click="exportList">导出</el-button>
    </div>
  </div>
  <div class="dataList">
    <el-table
      ref="multipleTableRef"
      :data="dataList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      border
      size="small"
      :height="hHeight + 'px'"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属单位" prop="depId">
        <template #default="scope">
          <div>{{ depIdName(scope.row.depId) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" prop="facilityName" />
      <el-table-column label="设备分类" prop="facilitySort" />
      <el-table-column label="设备分级" prop="facilityLevel" />
      <el-table-column label="规格型号" prop="specificationModel" />
      <el-table-column label="设备序列号" prop="facilitySerialNumber" />
      <el-table-column label="设备地点" prop="facilityLocations" />
      <el-table-column label="资产编号" prop="assetNumber" width="120" />
      <el-table-column label="设备状态" prop="facilityState">
        <template #default="scope">
          <div>{{ facilityStateName(scope.row.facilityState) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="数量" prop="facilityNumbers" />
      <el-table-column label="单位" prop="unit" />
      <el-table-column
        label="供应商/厂家"
        prop="facilitySupplier"
        width="120"
      />
      <el-table-column
        label="是/否纳入特许经营权"
        prop="franchising"
        width="140"
      />
      <el-table-column label="采购价格" prop="purchasePrice" />
      <el-table-column label="采购时间" prop="purchaseTime" width="100" />
      <el-table-column label="开始使用时间" prop="startTime" width="100" />
      <el-table-column label="保修期限" prop="guaranteeTime" />
      <el-table-column label="报废期限" prop="scrapTime" />
      <el-table-column label="是否联网" prop="networking" />
      <el-table-column
        label="主要技术参数"
        prop="technicalParameter"
        width="100"
      />
      <el-table-column
        label="主要零部件及参数"
        prop="partsParameters"
        width="130"
      />
      <el-table-column
        label="使用/安装说明书（附件）"
        prop="instructionManual"
        width="180"
      >
        <template #default="scope">
          <div class="preview">
            <span style="margin-right: 10px">{{
              scope.row.instructionManual
                ? scope.row.instructionManual
                : scope.row.instructionManualPath
            }}</span>
            <el-tag
              v-if="scope.row.instructionManualPath"
              class="ml-2"
              size="small"
              type="success"
              @click="downloadFile(scope.row.instructionManualPath)"
              style="cursor: pointer"
              >下载</el-tag
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="设备操作规程（附件）"
        prop="operatingProcedure"
        width="180"
      >
        <template #default="scope">
          <div class="preview">
            <span style="margin-right: 10px">{{
              scope.row.operatingProcedure
                ? scope.row.operatingProcedure
                : scope.row.operatingProcedurePath
            }}</span>
            <el-tag
              v-if="scope.row.operatingProcedurePath"
              class="ml-2"
              size="small"
              type="success"
              @click="downloadFile(scope.row.operatingProcedurePath)"
              style="cursor: pointer"
              >下载</el-tag
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="维修记录（附件）"
        prop="maintenanceRecord"
        width="180"
      >
        <template #default="scope">
          <div class="preview">
            <span style="margin-right: 10px">{{
              scope.row.maintenanceRecord
                ? scope.row.maintenanceRecord
                : scope.row.maintenanceRecordPath
            }}</span>
            <el-tag
              v-if="scope.row.maintenanceRecordPath"
              class="ml-2"
              size="small"
              type="success"
              @click="downloadFile(scope.row.maintenanceRecordPath)"
              style="cursor: pointer"
              >下载</el-tag
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="安装程序（附件）"
        prop="facilityInstaller"
        width="180"
      >
        <template #default="scope">
          <div class="preview">
            <span style="margin-right: 10px">{{
              scope.row.facilityInstaller
                ? scope.row.facilityInstaller
                : scope.row.facilityInstallerPath
            }}</span>
            <el-tag
              v-if="scope.row.facilityInstallerPath"
              class="ml-2"
              size="small"
              type="success"
              @click="downloadFile(scope.row.facilityInstallerPath)"
              style="cursor: pointer"
              >下载</el-tag
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="设备二维码（附件）"
        prop="twoDimensionalCode"
        width="180"
      >
        <template #default="scope">
          <div class="preview">
            <span style="margin-right: 10px">{{
              scope.row.twoDimensionalCode
            }}</span>
            <el-tag
              v-if="scope.row.twoDimensionalCode"
              class="ml-2"
              size="small"
              @click="
                handlePictureCardPreview(
                  scope.row.twoDimensionalCode,
                  'twoDimensionalCode'
                )
              "
              style="cursor: pointer"
              >预览</el-tag
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="设备照片（附件）"
        prop="ficilityPhoto"
        width="180"
      >
        <template #default="scope">
          <div class="preview">
            <span style="margin-right: 10px">{{
              scope.row.ficilityPhoto
            }}</span>
            <el-tag
              v-if="scope.row.ficilityPhoto"
              class="ml-2"
              size="small"
              @click="
                handlePictureCardPreview(
                  scope.row.twoDimensionalCode,
                  'ficilityPhoto'
                )
              "
              style="cursor: pointer"
              >预览</el-tag
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="设备合同（附件）"
        prop="ficilityContract"
        width="180"
      >
        <template #default="scope">
          <div class="preview">
            <span style="margin-right: 10px">{{
              scope.row.ficilityContract
            }}</span>
            <el-tag
              v-if="scope.row.ficilityContract"
              class="ml-2"
              size="small"
              type="success"
              @click="downloadFile(scope.row.ficilityContract)"
              style="cursor: pointer"
              >下载</el-tag
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" />
      <el-table-column label="操作" fixed="right" width="65">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <!-- <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >Delete</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-dialog v-model="addDialogVisible" title="新增设备" width="70%">
    <addInfo
      v-if="addDialogVisible"
      ref="addInfoDialogRef"
      @closed="referceDate()"
    ></addInfo>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit()"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="editDialogVisible" title="修改设备信息" width="70%">
    <editInfo
      v-if="editDialogVisible"
      ref="editInfoDialogRef"
      @closed="referceDate()"
      :currentEditInfo="currentEditInfo"
    ></editInfo>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editSubmit()"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="batchAddDialogVisible" title="批量新增" width="40%">
    <el-form
      ref="batchAddRef"
      :model="batchAddForm"
      :rules="rules"
      label-width="150px"
      class="demo-ruleForm"
    >
      <el-form-item
        label="新增设备数量"
        prop="batchAddNumber"
        class="demo-ruleForm-item"
      >
        <el-input-number
          v-model="batchAddForm.batchAddNumber"
          :min="1"
          :max="200"
          style="width: 200px"
        />
        <span style="margin-left: 10px; color: #999"
          >新增条数限制为1-200条</span
        >
      </el-form-item>

      <el-form-item
        label="所属单位"
        prop="facilitySort"
        class="demo-ruleForm-item"
      >
        <el-select
          v-model="batchAddForm.depId"
          placeholder="请选择"
          style="width: 200px"
          @change="batchAddDepIdChange"
        >
          <el-option
            v-for="item in batchAdddepIdList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="设备分类"
        prop="facilitySort"
        class="demo-ruleForm-item"
      >
        <el-select
          v-model="batchAddForm.facilitySort"
          placeholder="请选择"
          style="width: 200px"
        >
          <el-option
            v-for="item in facilitySortList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="batchAddDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="batchAddSubmit()"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
    v-model="batchAddDetailDialogVisible"
    title="设备批量新增"
    width="85%"
  >
    <batchAddDetail
      v-if="batchAddDetailDialogVisible"
      ref="batchAddDetailDialogRef"
      @closed="referceDate()"
      :currentBatchAddInfo="batchAddForm"
    ></batchAddDetail>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="batchAddDetailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="batchAddDetailSubmit()">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog
    v-model="batchEditDetailDialogVisible"
    title="设备批量新增"
    width="85%"
  >
    <batchEditDetail
      v-if="batchEditDetailDialogVisible"
      ref="batchEditDetailDialogRef"
      @closed="referceDate()"
      :currentBatchEditInfo="currentBatchEditInfo"
    ></batchEditDetail>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="batchEditDetailDialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" @click="batchEditDetailSubmit()">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="imgDialogVisible" :title="imgDialogTitle">
    <img w-full :src="dialogImageUrl" style="width: 100%" />
  </el-dialog>
</template>

<script setup>
import { reactive, ref, onMounted, nextTick } from "vue";
import equipmentHttp from "@/https/equipment.js";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import addInfo from "./add.vue";
import editInfo from "./edit.vue";
import batchAddDetail from "./batchAdd.vue";
import batchEditDetail from "./batchEdit.vue";
import { ElMessage } from "element-plus";
let searchForm = reactive({
  assetNumber: "",
  depId: "",
  facilityLevel: "",
  facilityLocations: "",
  facilityName: "",
  facilitySort: "",
  facilityState: "",
  facilitySupplier: "",
  specificationModel: "",
});
let batchAddForm = reactive({
  batchAddNumber: 1,
  depId: "",
  facilitySort: "",
});
const rules = ref({
  batchAddNumber: [{ required: true, message: "请输入", trigger: "blur" }],
  depId: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  facilitySort: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
});
const localTypeUnit = ref(Storage.localGet("depId"));
searchForm.depId = localTypeUnit.value;
let equipmentOverview = ref({});
const depIdList = ref([
  { label: "全部", value: "1" },
  { label: "星沙厂", value: "2" },
  { label: "城西厂", value: "3" },
  { label: "城北厂", value: "4" },
  { label: "城南厂", value: "5" },
  { label: "城东厂", value: "6" },
]);
const batchAdddepIdList = ref([
  { label: "星沙厂", value: "2" },
  { label: "城西厂", value: "3" },
  { label: "城北厂", value: "4" },
  { label: "城南厂", value: "5" },
]);
const depIdName = (id) => {
  return id == "1"
    ? "公司"
    : id == "2"
    ? "星沙厂"
    : id == "3"
    ? "城西厂"
    : id == "4"
    ? "城北厂"
    : "城南厂";
};
const facilityStateName = (id) => {
  return id == "1"
    ? "在用"
    : id == "2"
    ? "备用"
    : id == "3"
    ? "维修"
    : id == "4"
    ? "报废"
    : "其他";
};
const facilityLevelList = ref([
  { label: "一级", value: "一级" },
  { label: "二级", value: "二级" },
  { label: "三级", value: "三级" },
]);
const facilitySortList = ref([]);
const facilityStateList = ref([
  { label: "在用", value: "1" },
  { label: "备用", value: "2" },
  { label: "维修", value: "3" },
  { label: "报废", value: "4" },
  { label: "其他", value: "5" },
]);
const dataList = ref([]);
let addDialogVisible = ref(false);
let editDialogVisible = ref(false);
let batchAddDialogVisible = ref(false);
let batchAddDetailDialogVisible = ref(false);
let batchEditDetailDialogVisible = ref(false);
let imgDialogVisible = ref(false);

const depIdChange = () => {
  searchForm.facilitySort = "";
  getFacilitySort();
};
const batchAddDepIdChange = () => {
  batchAddForm.facilitySort = "";
  batchAddGetFacilitySort();
};

const hHeight = ref(0);
onMounted(() => {
  hHeight.value = document.documentElement.clientHeight - 350;
  search();
  getFacilitySort();
});
const getFacilitySort = () => {
  equipmentHttp.getFacilitySort(searchForm.depId).then((res) => {
    facilitySortList.value = [];
    res.data.data.forEach((item) => {
      facilitySortList.value.push({
        label: item,
        value: item,
      });
    });
  });
};
const batchAddGetFacilitySort = () => {
  equipmentHttp.getFacilitySort(batchAddForm.depId).then((res) => {
    facilitySortList.value = [];
    res.data.data.forEach((item) => {
      facilitySortList.value.push({
        label: item,
        value: item,
      });
    });
  });
};
const facilitySituation = () => {
  equipmentHttp.facilitySituation(searchForm.depId).then((res) => {
    if (res.data.code == 200) {
      console.log(res.data);
      nextTick(() => {
        equipmentOverview.value = res.data.data;
      });
    }
  });
};
const search = () => {
  equipmentHttp.queryFacility(searchForm).then((res) => {
    if (res.data.code == 200) {
      dataList.value = res.data.data;
    }
  });
  facilitySituation();
};
const reset = () => {
  searchForm = {
    assetNumber: "",
    depId: "",
    facilityLevel: "",
    facilityLocations: "",
    facilityName: "",
    facilitySort: "",
    facilityState: "",
    facilitySupplier: "",
    specificationModel: "",
  };
  search();
};
let rowDataList = ref([]);
const handleSelectionChange = (rowData) => {
  console.log(rowData);
  rowDataList.value = rowData;
};
const add = () => {
  console.log(1111);
  addDialogVisible.value = true;
};
let currentEditInfo = ref();
const handleEdit = (row) => {
  console.log("handleEdit");
  editDialogVisible.value = true;
  nextTick(() => {
    currentEditInfo.value = row;
  });
  console.log(currentEditInfo.value, row);
};
const handleClose = () => {};
const batchAdd = () => {
  console.log(1111);
  batchAddDialogVisible.value = true;
};
let currentBatchEditInfo = ref([]);
const batchEdit = () => {
  console.log("batchEdit");
  if (rowDataList.value.length > 0) {
    batchEditDetailDialogVisible.value = true;
    currentBatchEditInfo.value = JSON.parse(JSON.stringify(rowDataList.value));
  } else {
    ElMessage({
      message: "请至少勾选一条数据",
      type: "warning",
    });
  }
};
const exportList = () => {
  console.log(1111);
  equipmentHttp.exportFacility(searchForm).then((response) => {
    console.log(response);
    const content = response.data;
    const blob = new Blob([content], { type: "application/ms-excel" });
    let fileName = `设备台账.xls`;
    if ("download" in document.createElement("a")) {
      // 非IE下载
      const elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName);
    }
  });
};
const addInfoDialogRef = ref();
const submit = () => {
  addInfoDialogRef.value.submitInfo();
};
const editInfoDialogRef = ref();
const editSubmit = () => {
  editInfoDialogRef.value.editSubmit();
};
const batchAddRef = ref();
const batchAddSubmit = () => {
  console.log(1);
  if (!batchAddRef) return;
  batchAddRef.value.validate((valid, fields) => {
    if (valid) {
      batchAddDialogVisible.value = false;
      batchAddDetailDialogVisible.value = true;
    } else {
    }
  });
};
const batchAddDetailDialogRef = ref();
const batchAddDetailSubmit = () => {
  batchAddDetailDialogRef.value.batchAddDetailSubmit();
};

const batchEditDetailDialogRef = ref();
const batchEditDetailSubmit = () => {
  batchEditDetailDialogRef.value.batchEditDetailSubmit();
};
const referceDate = () => {
  addDialogVisible.value = false;
  editDialogVisible.value = false;
  batchAddDetailDialogVisible.value = false;
  batchEditDetailDialogVisible.value = false;
  search();
};
let dialogImageUrl = ref();
let imgDialogTitle = ref();
const handlePictureCardPreview = (url, type) => {
  imgDialogTitle.value =
    type == "twoDimensionalCode" ? "设备二维码" : "设备照片";
  imgDialogVisible.value = true;
  dialogImageUrl.value = "http://47.106.144.138" + url;
  // dialogImageUrl.value = "http://47.106.144.138/facilityFile/10-4.png";
};
const downloadFile = (url) => {
  window.open("http://47.106.144.138" + url);
};
</script>

<style scoped lang="less">
.filter {
  flex-wrap: wrap;
  display: flex;
  flex-direction: row;
  align-items: center;
  .filter-item {
    margin: 0 15px 15px 0px;
    display: flex;
    flex-direction: row;
    align-items: center;
    label {
      font-size: 14px;
      color: #333;
      display: inline-block;
      white-space: nowrap;
    }
  }
}
.options {
  margin: 20px 0 15px;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  .ml-2 {
    margin-right: 10px;
  }
}
.preview {
  display: flex;
  flex-direction: row;
  align-items: center;
}
</style>
